import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 按需加载模块
const Login = () => import('@/views/login/SysLogin.vue')
const OaMain = () => import('@/views/main/OaMain.vue')
const CommonForm = () => import('@/views/main/CommonForm.vue')
const IM = () => import('@/views/workman/IM.vue')
const RedisRabbitMQ = () => import('@/views/redis/RedisRabbitMQ.vue')

Vue.use(VueRouter)

// 路由列表
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/main',
    component: OaMain,
    children: [
      {
        path: '/workman/im',
        component: IM
      }, {
        path: '/redis/rr',
        component: RedisRabbitMQ
      }
    ]
  },
  {
    path: '/form',
    component: CommonForm
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 拦截器
// 白名单
const whitList = ['/', '/login']
// 登录页面数组
// const loginArr = ['/login']

router.beforeEach((to, from, next) => {
  // 1. to 往哪里去 对象
  // to.path 不包含查询参数  to.fullPath 包含查询参数
  // 2. from 从哪来 对象
  // 3. next()是否放行
  // 如果next()就是放行
  // 如果next(路径)拦截到某个路径页面

  // 如果非拦截页面
  if (whitList.includes(to.path)) {
    // 如果为登录页 判断有无token 有的话跳转到main 如果有伪造的token则在request的通用返回中进行处理
    // if (loginArr.includes(to.path) && store.state.user.userInfo.token) {
    //   next('/main')
    //   return
    // }
    // 正常跳转
    next()
    return
  }

  if (store.state.user.userInfo.token) {
    next()
    return
  }

  // 如果没有token则跳转到登录
  next('/login')
})

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) { return originalPush.call(this, location, onResolve, onReject) }
  return originalPush.call(this, location).catch((err) => err)
}

export default router
